#pragma once

#include "game_def.h"
#include "game_string.h"
#include <string>
#include <stddef.h>

static inline
std::string __bcd_bytes_to_string(const BYTE *bytes, size_t len)
{
  std::string tmp(len*2, '0');
  for (size_t i = 0; i < len; i++)
  {
    BYTE c = bytes[i];
    tmp[i * 2] = (c >> 4) + '0';
    tmp[i * 2 + 1] = (c & 0x0F) + '0';
  }
  return tmp;
}

static inline
size_t __bcd_bytes_from_string(BYTE *buf, size_t bufsize, const std::string &bcd_str)
{
  size_t i;
  size_t strlen = bcd_str.size();
  for (i = 0; i < bufsize; i++)
  {
    int idx1 = i * 2;
    int idx2 = i * 2 + 1;
    char c1 = strlen > (size_t)idx1 ? ((bcd_str[idx1] - '0') & 0xF) : 0;
    char c2 = strlen > (size_t)idx2 ? ((bcd_str[idx2] - '0') & 0xF) : 0;
    buf[i] = (c1 << 4) | c2;
  }
  return i;
}

// 数据转十六进制字符串
// space 每个数据间的空格个数
// col 几个数据换一次行，为0不换行
static inline
std::string __bytes_to_hex_string(const BYTE *bytes, size_t size, int space, int col)
{
  // 生成空格
  std::string space_str;
  for (int i = 0; i < space; ++i) {
    space_str += " ";
  }

  std::string tmp;
  int col_count = 0;
  for (size_t i = 0; i < size; ++i) {
    tmp += __string_format("%02X", bytes[i]);
    col_count++;
    tmp += (col_count != col) ? space_str : "\n";
    col_count = (col_count == col) ? 0 : col_count;
  }
  return tmp;
}
